﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.VModel;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 产品管理（错误代码：112001）
    /// </summary>
    public class ProductMgr
    {
        private Logger logger = LogManager.GetLogger(nameof(ProductMgr));
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 同步产品
        /// </summary>
        /// <param name="products">产品列表</param>
        public void AsyncProduct(List<VProduct> models)
        {
            var categories = mesDb.ProductCategories.AsNoTracking().Where(_ => _.Valid).ToList();
            var products = mesDb.Products.AsNoTracking().Where(_ => _.Valid).ToList();

            foreach (var product in models)
            {
                var categoryCode = (decimal)0;
                decimal.TryParse(product.CategoryCode, out categoryCode);
                if (categoryCode > 0)
                {
                    product.CategoryCode = categoryCode.ToString("0.0000");
                }
                else if (categoryCode == 0)
                {
                    product.CategoryCode = "0.0000";
                }
                var category = categories.FirstOrDefault(_ => string.Equals(_.CategoryCode, product.CategoryCode, StringComparison.CurrentCultureIgnoreCase));
                if (category == null)
                {
                    logger.Error($"异常物料：ProductCode：{product.ProductCode}，ProductName：{product.ProductName}，CategoryCode：{product.CategoryCode}");
                }
                product.CreateTime = DateTime.Now;
                product.CategoryCode = category?.CategoryCode;
                product.CategoryName = category?.CategoryName;
            }

            models = models.Where(_ => !string.IsNullOrWhiteSpace(_.CategoryCode)).ToList();

            var existProductCodes = products.Select(_ => _.ProductCode).Distinct().ToList();
            var newProducts = models.Where(_ => !existProductCodes.Contains(_.ProductCode, StringComparer.CurrentCultureIgnoreCase)).ToList();
            var existProducts = models.Where(_ => existProductCodes.Contains(_.ProductCode, StringComparer.CurrentCultureIgnoreCase)).ToList();

            foreach (var product in existProducts)
            {
                var entity = products.FirstOrDefault(_ => string.Equals(_.ProductCode, product.ProductCode, StringComparison.CurrentCultureIgnoreCase));

                mesDb.Products.Attach(entity);
                entity.ProductName = product.ProductName;
                entity.Specifications = product.Specifications;
                entity.CategoryCode = product.CategoryCode;
                entity.CategoryName = product.CategoryName;
                entity.MainUnitCode = product.MainUnitCode;
                entity.MainUnitName = product.MainUnitName;
                entity.ProductionOrigin = product.ProductionOrigin;
                entity.ModifyBy = 0;
                entity.ModifyTime = DateTime.Now;
            }
            if (newProducts.Any())
            {
                var entities = Mapper.Map<List<Product>>(newProducts);
                mesDb.Products.AddRange(entities);
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询物料信息
        /// </summary>
        /// <param name="productCode">物料编码</param>
        /// <returns>物料信息</returns>
        public VProduct GetProduct(string productCode)
        {
            var entity = mesDb.Products.AsNoTracking().FirstOrDefault(_ => _.ProductCode == productCode && _.Valid);
            return Mapper.Map<VProduct>(entity);
        }

        /// <summary>
        /// 根据分类查询所有料号
        /// </summary>
        /// <param name="categoryName">分类名称</param>
        /// <returns></returns>
        public List<VProduct> QueryProducts(string categoryName)
        {
            var entities = mesDb.Products.AsNoTracking().Where(_ => _.CategoryName == categoryName && _.Valid).ToList();
            return Mapper.Map<List<VProduct>>(entities);
        }
    }
}
